const { pool } = require("../../db");
const jwt = require("jsonwebtoken");
// 登录
exports.login = async (username, password) => {
  const query = `select * from admin where username = '${username}' and password = '${password}'`;
  const [rows] = await pool.query(query);
  if (rows.length > 0) {
    const token = jwt.sign(
      { id: rows[0].id, username: rows[0].username },
      process.env.SECRETKEY,
      {
        expiresIn: "2d",
      }
    );
    return {
      code: 200,
      status: "success",
      message: "登录成功",
      data: token,
    };
  } else {
    return { code: 500, message: "用户名或密码错误" };
  }
};
// 获取用户信息
exports.getAllUserInfo = async (id, username, req) => {
  const query = `SELECT m.name,r.rolename FROM admin a JOIN roles r ON a.role = r.id JOIN roles_menus rm ON r.id = rm.role_id JOIN menus m ON rm.menu_id = m.id  WHERE a.id = '${id}'`;
  try {
    const [rows] = await pool.query(query);
    const routes = [];
    rows.forEach((item) => {
      routes.push(item.name);
    });
    return {
      code: 200,
      message: "成功",
      ok: true,
      data: {
        routes,
        roles: rows[0].rolename,
        name: username,
        avatar: `${req.protocol}://${req.headers.host}/public/images/logo.png`,
      },
    };
  } catch (error) {
    console.log(error);
    return {
      code: 500,
      message: "失败",
      ok: false,
    };
  }
};
// 获取所有管理员信息
exports.getAllAdminInfo = async (page, limit, keyword, offset) => {
  let query = "";
  let query1 = "";
  if (keyword) {
    query = `SELECT a.*,r.rolename from admin a left join roles r on a.role = r.id where username like '%${keyword}%' limit ${limit} offset ${offset}`;
    query1 = `select count(*) from admin where username like '%${keyword}%'`;
  } else {
    query = `SELECT a.*,r.rolename from admin a left join roles r on a.role = r.id limit ${limit} offset ${offset}`;
    query1 = `select count(*) from admin`;
  }
  try {
    const [rows] = await pool.query(query);
    const [counts] = await pool.query(query1);
    return {
      code: 200,
      message: "获取成功",
      ok: true,
      data: rows,
      total: counts[0]["count(*)"],
    };
  } catch (error) {
    return {
      code: 500,
      message: "获取失败",
      ok: false,
      data: null,
    };
  }
};
// 添加admin用户
exports.addAdmin = async (username, password) => {
  const query = `insert into admin(username,password) values('${username}','${password}')`;
  try {
    await pool.query(query);
    return {
      code: 200,
      message: "添加成功",
      ok: true,
      data: null,
    };
  } catch (error) {
    return {
      code: 500,
      message: "添加失败",
      ok: false,
      data: null,
    };
  }
};
// 修改admin用户
exports.updateAdmin = async (id, username) => {
  const query = `update admin set username='${username}' where id='${id}'`;
  try {
    await pool.query(query);
    return {
      code: 200,
      message: "修改成功",
      ok: true,
      data: null,
    };
  } catch (error) {
    return {
      code: 500,
      message: "修改失败",
      ok: false,
      data: null,
    };
  }
};
// 删除admin用户
exports.deleteAdmin = async (id) => {
  const query = `delete from admin where id='${id}'`;
  try {
    await pool.query(query);
    return {
      code: 200,
      message: "删除成功",
      ok: true,
      data: null,
    };
  } catch (error) {
    return {
      code: 500,
      message: "删除失败",
      ok: false,
      data: null,
    };
  }
};
// 获取权限
exports.getPermission = async (id) => {
  const query = `select * from roles`;
  const query1 = `select role from admin where id='${id}'`;
  let assignRoles = "";

  try {
    const [rows] = await pool.query(query);
    const [rows1] = await pool.query(query1);
    assignRoles = rows1[0].role;
    return { code: 200, data: { allRolesList: rows, assignRoles } };
  } catch (error) {
    return { code: 404, data: null };
  }
};
// 分配权限
exports.assignPermission = async (userId, roleId) => {
  const query = `update admin set role=${roleId} where id='${userId}'`;
  try {
    await pool.query(query);
    return { code: 200, data: null };
  } catch (error) {
    return { code: 404, data: null };
  }
};
// 批量删除用户
exports.deleteAdmins = async (id) => {
  const query = `DELETE FROM admin WHERE id IN (?)`;
  try {
    await pool.query(query, [id]);
    return { code: 200, data: null };
  } catch (error) {
    return { code: 500, data: null };
  }
};
